//
//  UIApplication+SGExtension.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/19.
//  Copyright © 2025 考拉🐨. All rights reserved.
//

import UIKit

extension UIApplication: SpadgerCompatible {}

public extension Spadger where Base == UIApplication {
    
    /// app商店链接
    @discardableResult
    static func AppStoreUrlWithID(_ appleID: String) -> String {
        return "itms-apps://itunes.apple.com/app/id\(appleID)?mt=8"
    }
    
    /// app商店链接
    static func openAppStoreUrlWithID(_ appleID: String)  {
        let appStoreUrl = AppStoreUrlWithID(appleID)
        openThirdPartyApp(thirdPartyAppDeeplink: appStoreUrl) { _ in
        }
    }
    
    /// app详情链接
    @discardableResult
    static func appDetailUrlWithID(_ appleID: String) -> String {
        let detailUrl = "http://itunes.apple.com/cn/lookup?id=\(appleID)"
        return detailUrl
    }
    
    /// 评分App链接
    @discardableResult
    static func rateAppUrlWithID(_ appleID: String) -> String {
        return "itms-apps://itunes.apple.com/app/id\(appleID)?action=write-review"
    }
    
    /// 打开评分App链接
    static func openRateAppUrlWithID(_ appleID: String) {
        let rateAppUrl = rateAppUrlWithID(appleID)
        openThirdPartyApp(thirdPartyAppDeeplink: rateAppUrl) { _ in
        }
    }
    
    /// 设置APP是否常亮，是否禁止自动锁屏
    static func isIdleTimerDisabled(_ isIdleTimerDisabled: Bool) {
        UIApplication.shared.isIdleTimerDisabled = isIdleTimerDisabled
    }
    
    /// APP主动崩溃
    static func exitApp() {
        // 默认的程序结束函数
        abort()
    }
}

/// 系统app
public enum SGSystemAppType: String {
    case safari = "http://"
    case googleMaps = "http://maps.google.com"
    case Phone = "tel://"
    case SMS = "sms://"
    case Mail = "mailto://"
    case iBooks = "ibooks://"
    case AppStore = "itms-apps://itunes.apple.com"
    case Music = "music://"
    case Videos = "videos://"
}

public extension Spadger where Base == UIApplication {
    // 跳转URL
    static func openUrl(url: URL, complete: @escaping ((Bool) -> Void)) {
        // iOS 10.0 以后
        UIApplication.shared.open(url, options: [:]) { success in
            complete(success)
        }
    }
    
    /// 打开系统app
    /// - Parameter type: 系统app类型
    static func openSystemApp(type: SGSystemAppType, complete: @escaping ((Bool) -> Void)) {
        UIApplication.sg.openUrl(url: URL(string: type.rawValue)!, complete: complete)
    }
    
    /// 打开第三方app
    /// - Parameter thirdPartyAppDeeplink: 第三方app的Deeplink
    static func openThirdPartyApp(thirdPartyAppDeeplink: String, complete: @escaping ((Bool) -> Void)) {
        guard let url = URL(string: thirdPartyAppDeeplink) else {
            complete(false)
            return
        }
        UIApplication.sg.openUrl(url: url, complete: complete)
    }
}
